﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using VSSTQH.Properties;
using VSSTQH.DataAccess;
using VSSTQH.Reports;

namespace VSSTQH
{
    public partial class FrmPO : Form
    {
        #region Ctors

        /// <summary>
        /// Constructor for create new status
        /// </summary>
        public FrmPO()
        {
            InitializeComponent();
            Initialize();
        }

        #endregion

        #region Property Members
        public bool can = true;
        #endregion

        #region Vehicle Scale Property
        private POModel _currentPO;
        /// <summary>
        /// Vehicle Scale Property
        /// </summary>
        public POModel CurrentPO
        {
            get { return _currentPO; }
            set
            {
                if (_currentPO != value)
                {
                    _currentPO = value;
                }
            }
        }
        #endregion

        

        #region Events
        void cboVendorID_SelectedValueChanged(object sender, EventArgs e)
        {
            if (chkManual.Checked)
            {
                if (cboVendorID.Value != null)
                {
                    txtVendorID.Text = cboVendorID.Text;
                    txtVendorName.Text = cboVendorID.Value.ToString();
                }
                else
                {
                    txtVendorID.Text = String.Empty;
                    txtVendorName.Text = String.Empty;
                }
            }
        }

        void cboProductID_SelectedValueChanged(object sender, EventArgs e)
        {
            if (chkManual.Checked)
            {
                if (cboProductID.Value != null)
                {
                    txtProductID.Text = cboProductID.Text;
                    txtProductName.Text = cboProductID.Value.ToString();
                }
                else
                {
                    txtProductID.Text = String.Empty;
                    txtProductName.Text = String.Empty;
                }
            }
        }

        void cboPoType_LostFocus(object sender, EventArgs e)
        {
            if (this.cboPoType.SelectedIndex > 0)
            {
                errorProvider.Clear();
                return;
            }
        }

        void lostFocus(object sender, EventArgs e)
        {
            if (this.cboPoType.SelectedIndex < 1)
            {
                errorProvider.SetError(cboPoType, Resources.NotChoosePOType);
                cboPoType.Focus();
                return;
            }
            if (txtIOCode.TextLength == 0) return;

            IList<POModel> collection;
            IList<POModel> infiles;

            IPODAO dataAccess = new PODAO();
            decimal inbound = 0;
            bool valid = Decimal.TryParse(this.txtIOCode.Text, out inbound);

            if (valid)
            {
                string filename = String.Empty;
                int potype = this.cboPoType.SelectedIndex;
                switch (potype)
                {
                    case 1:
                        filename = String.Format(Common.MM_S2C, inbound);
                        break;
                    case 2:
                        filename = String.Format(Common.SD_S2C, inbound);
                        break;
                }

                collection = dataAccess.GetBy(inbound, potype);

                if (File.Exists(filename) || collection != null)
                {
                    infiles = new List<POModel>();
                    IList<string[]> csv = parseCSV(filename);

                    foreach (var item in csv)
                        infiles.Add(POMapper.ToModel(item));
                    if (collection != null)
                        infiles = infiles.Concat(collection).ToList();

                    this.gridEXPo.DataSource = infiles;

                }
                else
                {
                    this.gridEXPo.DataSource = null;
                    Common.ShowAlert(Resources.InvalidInbound, txtIOCode.Text);
                }
            }

        }

        private void ClickButtonSave()
        {
            try
            {
                if (CurrentPO != null && ValidData())
                {
                    // Update Data
                    CurrentPO.VehicleID = txtVehicleID.Text;
                    CurrentPO.FirstWeight = (decimal)numFirstWeight.Value;
                    CurrentPO.SecondWeight = (decimal)numSecondWeight.Value;
                    DateTime temp;
                    if (DateTime.TryParse(mskScaleTime1.Text, out temp))
                        CurrentPO.FirstTime = temp;
                    if (DateTime.TryParse(mskScaleTime2.Text, out temp))
                        CurrentPO.SecondTime = temp;
                    CurrentPO.ActualWeight = (decimal)numWeight.Value;
                    CurrentPO.ActualWeight2 = (decimal)numActualWeight2.Value;
                    CurrentPO.Unit = txtUnit.Text;
                    CurrentPO.Unit2 = cboUnit2.Text;
                    CurrentPO.ProductID = txtProductID.Text;
                    CurrentPO.ProductName = txtProductName.Text;
                    CurrentPO.VendorID = txtVendorID.Text;
                    CurrentPO.VendorName = txtVendorName.Text;
                    CurrentPO.PoID = txtPOID.Text;
                    CurrentPO.Inbound = Convert.ToDecimal(numInbound.Value);
                    CurrentPO.InboundWeight = Convert.ToDecimal(numInboundWeight.Value);
                    CurrentPO.WBS = txtWBS.Text;
                    CurrentPO.Location = txtLocation.Text;
                    CurrentPO.PoType = cboPoType.SelectedIndex;

                    // Write to Database
                    IPODAO dao = new PODAO();
                    bool isNew = false;
                    if (dao.Save(CurrentPO, ref isNew))
                    {
                        // Only write to file PO has secondweight > 0

                        decimal inbound = 0;
                        bool valid = Decimal.TryParse(this.txtIOCode.Text, out inbound);

                        if (valid)
                        {
                            string filename = String.Empty;
                            switch (this.cboPoType.SelectedIndex)
                            {
                                case 1:
                                    filename = String.Format(Common.MM_C2S, inbound);
                                    break;
                                case 2:
                                    filename = String.Format(Common.SD_C2S, inbound);
                                    break;
                            }

                            IList<POModel> completedPO = dao.GetBy(inbound, this.cboPoType.SelectedIndex, true);

                            if (completedPO != null && completedPO.Count > 0)
                            {
                                if (!File.Exists(filename))
                                {
                                    using (System.IO.FileStream fs = System.IO.File.Create(filename))
                                    {
                                        StreamWriter sw = new StreamWriter(fs);

                                        foreach (var item in completedPO)
                                        {
                                            sw.WriteLine(POMapper.ToCSV(item));
                                        }

                                        sw.Flush();
                                        fs.Close();
                                    }
                                }
                                else
                                {
                                    using (System.IO.FileStream fs = File.OpenWrite(filename))
                                    {
                                        StreamWriter sw = new StreamWriter(fs);

                                        foreach (var item in completedPO)
                                        {
                                            sw.WriteLine(POMapper.ToCSV(item));
                                        }

                                        sw.Flush();
                                        fs.Close();
                                    }
                                }
                            }

                            #region Process A line
                            //if (!File.Exists(filename))
                            //{
                            //    using (System.IO.FileStream fs = System.IO.File.Create(filename))
                            //    {
                            //        StreamWriter sw = new StreamWriter(fs);
                            //        sw.WriteLine(POMapper.ToCSV(CurrentPO));

                            //        sw.Flush();
                            //        fs.Close();
                            //    }
                            //}
                            //else
                            //{
                            //    //if (isNew)
                            //    //{
                            //    using (StreamWriter w = File.AppendText(filename))
                            //    {
                            //        w.WriteLine(POMapper.ToCSV(CurrentPO));
                            //        // Close the writer and underlying file.
                            //        w.Flush();
                            //        w.Close();
                            //    }


                            //    //}
                            //    //else
                            //    //{
                            //    //    string[] lines = File.ReadAllLines(filename);
                            //    //    string key = String.Format("{0},{1}", CurrentPO.Inbound, CurrentPO.SeqInbound);
                            //    //    int index = -1;
                            //    //    for (int i = 0; i < lines.Length; i++)
                            //    //    {
                            //    //        if (lines[i].StartsWith(key))
                            //    //        {
                            //    //            index = i;
                            //    //            break;
                            //    //        }
                            //    //    }
                            //    //    if (index > -1)
                            //    //    {
                            //    //        lines[index] = POMapper.ToCSV(CurrentPO);
                            //    //        File.WriteAllLines(filename, lines);
                            //    //    }
                            //    //    else
                            //    //    {
                            //    //        using (StreamWriter w = File.AppendText(filename))
                            //    //        {
                            //    //            w.WriteLine(POMapper.ToCSV(CurrentPO));
                            //    //            // Close the writer and underlying file.
                            //    //            w.Flush();
                            //    //            w.Close();
                            //    //        }

                            //    //        //FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
                            //    //        //StreamWriter sw = new StreamWriter(fs);

                            //    //        //sw.BaseStream.Seek(0, SeekOrigin.End);
                            //    //        //sw.WriteLine(POMapper.ToCSV(CurrentPO));

                            //    //        //sw.Flush();
                            //    //        //fs.Close();
                            //    //    }
                            //    //}
                            //}
                            #endregion
                        }

                        // End if Save

                        this.chkInputScale.Checked = false;
                        this.chkManual.Checked = false;
                    }

                    this.gridEXPo.Refetch();

                }
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                SendKeys.Send("{TAB}");
            }
            if (e.KeyCode == Keys.F5 && e.Control)
            {
                this.numFirstWeight.Value = 0;
                this.numSecondWeight.Value = 0;
                this.numFirstWeight.Enabled = true;
                this.numSecondWeight.Enabled = true;
            }
        }

        void numFirstWeight_LostFocus(object sender, EventArgs e)
        {
            if ((decimal)numFirstWeight.Value > 0)
            {
                this.mskScaleTime1.Text = String.Format("{0:d} {0:HH:mm}", DateTime.Now);
                this.numFirstWeight.Enabled = false;
            }
        }

        void numSecondWeight_LostFocus(object sender, EventArgs e)
        {
            if ((decimal)numSecondWeight.Value > 0)
            {
                this.mskScaleTime2.Text = String.Format("{0:d} {0:HH:mm}", DateTime.Now);
                this.numSecondWeight.Enabled = false;
            }
        }

        void WeightValueChanged(object sender, EventArgs e)
        {
            decimal firstWeight = (decimal)this.numFirstWeight.Value;
            decimal secondWeight = (decimal)this.numSecondWeight.Value;
            if (firstWeight > 0 && secondWeight > 0)
            {
                decimal compare = firstWeight - secondWeight;
                this.numWeight.Value = Math.Abs(compare);
            }
            else
            {
                this.numWeight.Value = 0;
            }
        }

        void chkManual_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            bool b = checkBox.Checked;

            txtVendorID.Visible = !b;
            txtProductID.Visible = !b;
            cboVendorID.Visible = b;
            cboProductID.Visible = b;

            if (b)
            {
                if (this.chkInputScale.Checked)
                {
                    this.chkInputScale.Checked = false;
                }
                this.numFirstWeight.Enabled = true;
                this.numSecondWeight.Enabled = true;
            }

            this.numInbound.ReadOnly = !b;
            this.numSeq.ReadOnly = !b;
            this.txtPOID.ReadOnly = !b;
            this.cboVendorID.Enabled = b;
            //this.txtVendorName.ReadOnly = !b;
            this.cboProductID.Enabled = b;
            //this.txtProductName.ReadOnly = !b;
            this.numInboundWeight.ReadOnly = !b;
            this.txtUnit.ReadOnly = !b;
            this.txtWBS.ReadOnly = !b;

            // Set permission
            bool IsAdmin = (Common.UserLogin.GroupID == 1);

            if (IsAdmin)
            {
                this.numFirstWeight.ReadOnly = !b;
                this.numSecondWeight.ReadOnly = !b;
            }
            else
            {
                this.numFirstWeight.ReadOnly = true;
                this.numSecondWeight.ReadOnly = true;
            }
        }

        void chkInputScale_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            bool b = checkBox.Checked;

            //this.numFirstWeight.ReadOnly = b;
            //this.numSecondWeight.ReadOnly = b;
            this.cboPoType.Enabled = !b;

            if (b)
            {
              //  this.grbChooseWeight.Enabled = true;
                if (this.rdtFirstWeight.Checked == false && this.rdtSecondWeight.Checked ==false)
                {
                    MessageBox.Show("Bạn phải chọn Cân 1 hay Cân 2 trước.");
                    this.chkInputScale.Checked = false;
                    return;
                }

                //can = true : Can 1 ,  can =false : Can 2

                if (can)
                {
                    if ((decimal)this.numFirstWeight.Value > 0)
                    {
                        // Exists First weight
                        this.numFirstWeight.Enabled = false;
                        if ((decimal)this.numSecondWeight.Value > 0)
                        {
                            this.numSecondWeight.Enabled = false;
                        }
                        else
                        {
                            // Check get second weight
                            // this.rdtSecondWeight.Checked = true;
                            this.numSecondWeight.Enabled = true;
                            this.numSecondWeight.Focus();
                        }
                    }
                    else
                    {
                        // Check get first weight
                        // this.rdtFirstWeight.Checked = true;
                        this.numFirstWeight.Enabled = true;
                        this.numFirstWeight.Focus();
                    }

                    if (Common.Port2.IsOpen)
                    {
                        FreeEventSerialPort2();
                    }
                    Common.Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
                }
                else
                {
                    if (Common.Port.IsOpen)
                    {
                        FreeEventSerialPort();
                    }
                    Common.Port2.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived2);
                }


                

                if (this.chkManual.Checked)
                {
                    this.chkManual.Checked = false;
                }
            }
            
        }

        void gridEXPo_SelectionChanged(object sender, EventArgs e)
        {
            if (this.gridEXPo.CurrentRow != null)
            {
                CurrentPO = this.gridEXPo.CurrentRow.DataRow as POModel;
                if (CurrentPO != null)
                {
                    //•	Số Inbound Delivery \ Outbound Delivery (*** Input ***)
                    //•	STT trên Inbound trong SAP
                    //•	Số PO
                    //•	Mã Vendor
                    //•	Tên Vendor
                    //•	Mã hàng
                    //•	Tên hàng
                    //•	Kho
                    //•	Số lượng inbound
                    //•	Đơn vị tính
                    //•	Tên hạng mục (WBS) 

                    this.numInbound.Value = CurrentPO.Inbound;
                    this.numSeq.Value = CurrentPO.SeqInbound;
                    this.txtPOID.Text = CurrentPO.PoID;
                    this.cboVendorID.Text = CurrentPO.VendorID;
                    this.txtVendorID.Text = CurrentPO.VendorID;
                    this.txtVendorName.Text = CurrentPO.VendorName;
                    this.cboProductID.Text = CurrentPO.ProductID;
                    this.txtProductID.Text = CurrentPO.ProductID;
                    this.txtProductName.Text = CurrentPO.ProductName;
                    this.txtLocation.Text = CurrentPO.Location;
                    this.numInboundWeight.Value = CurrentPO.InboundWeight;
                    this.txtUnit.Text = CurrentPO.Unit;
                    this.txtWBS.Text = CurrentPO.WBS;
                    this.txtVehicleID.Text = CurrentPO.VehicleID;
                    this.numActualWeight2.Value = CurrentPO.ActualWeight2;

                    this.numFirstWeight.Value = CurrentPO.FirstWeight;
                    this.numSecondWeight.Value = CurrentPO.SecondWeight;
                    this.mskScaleTime1.Text = String.Format("{0:d} {0:HH:mm}", CurrentPO.FirstTime);
                    this.mskScaleTime2.Text = String.Format("{0:d} {0:HH:mm}", CurrentPO.SecondTime);
                    if (CurrentPO.PoType.HasValue)
                        this.cboPoType.SelectedIndex = CurrentPO.PoType.Value;

                    //bool b = (CurrentPO.SecondWeight > 0);
                    //txtVehicleID.Enabled = !b;
                    //numActualWeight2.Enabled = !b;
                    //cboUnit2.Enabled = !b;
                    if (chkInputScale.Checked) chkInputScale.Checked = false;
                    if (chkManual.Checked) chkManual.Checked = false;
                }
            }
        }

        private void gridEXPo_FormattingRow(object sender, Janus.Windows.GridEX.RowLoadEventArgs e)
        {
            if (e.Row.Cells["POType"].Value == null) return;
            if (e.Row.Cells["POType"].Value.Equals(1))
            {
                e.Row.Cells["POType"].Text = "Nhập hàng";
            }
            else if (e.Row.Cells["POType"].Value.Equals(2))
            {
                e.Row.Cells["POType"].Text = "Xuất hàng";
            }
        }

        #endregion

        #region Initializes
        /// <summary>
        /// Initialize method
        /// </summary>
        private void Initialize()
        {
            #region Set value to some controls
            this.MaximizeBox = false;

            #endregion

            this.txtIOCode.LostFocus += new EventHandler(lostFocus);
            this.cboPoType.LostFocus += new EventHandler(cboPoType_LostFocus);
            this.btnSave.Click += new EventHandler(delegate
            {
                ClickButtonSave();
            });

            this.numFirstWeight.ValueChanged += new EventHandler(WeightValueChanged);
            this.numSecondWeight.ValueChanged += new EventHandler(WeightValueChanged);
            this.numFirstWeight.LostFocus += new EventHandler(numFirstWeight_LostFocus);
            this.numSecondWeight.LostFocus +=new EventHandler(numSecondWeight_LostFocus);
           
            this.rdtFirstWeight.CheckedChanged += new EventHandler(ChooseWeight_CheckChanged);
            this.rdtSecondWeight.CheckedChanged += new EventHandler(ChooseWeight_CheckChanged);
       
            this.chkInputScale.CheckedChanged += new EventHandler(chkInputScale_CheckedChanged);
            this.chkManual.CheckedChanged += new EventHandler(chkManual_CheckedChanged);
            this.btnReset1.Click += new EventHandler(delegate
            {
                this.numFirstWeight.Value = 0;
            });

            this.btnReset2.Click += new EventHandler(delegate
            {
                this.numSecondWeight.Value = 0;
            });

            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
            this.btnPrint.Click += new EventHandler(delegate
            {
                try
                {
                    crTicket report = new crTicket();
                    report.SetDataSource(CollectionExtensions<POModel>.ConvertToDataTable(new List<POModel>() { CurrentPO }, "VSSTQH_POModel"));

                    SettingApp setting = new SettingApp();

                    if (Common.CheckPrinter(setting.ReceiptPrintName))
                        report.PrintOptions.PrinterName = setting.ReportPrintName;
                    report.PrintOptions.ApplyPageMargins(new CrystalDecisions.Shared.PageMargins(setting.MarginLeft, setting.MarginTop, setting.MarginRight, setting.MarginBottom));

                    if (setting.IsPreviewReportPrint)
                    {
                        FrmPrintPreview form = new FrmPrintPreview(report);
                        form.ShowDialog();
                    }
                    else
                    {
                        report.PrintToPrinter(1, false, 0, 0);
                    }
                }
                catch (Exception ex)
                {
                    Common.ShowAlert(ex.Message);
                }
            });

            this.gridEXPo.SelectionChanged += new EventHandler(gridEXPo_SelectionChanged);
            this.gridEXPo.FormattingRow += new Janus.Windows.GridEX.RowLoadEventHandler(gridEXPo_FormattingRow);

            // Set permission
            bool IsAdmin = (Common.UserLogin.GroupID == 1);
            //this.chkManual.Visible = IsAdmin;

            this.chkInputScale.Checked = false;
            this.chkManual.Checked = false;

            LoadData();

            ToolTip tooltip = new ToolTip();
            tooltip.SetToolTip(this.chkInputScale, "Bạn có thể nhấn tổ hợp phím Control + F5 để reset 2 lần cân.");
        }
        #endregion

        #region Methods
        //Chon Can
        void ChooseWeight_CheckChanged(object sender, EventArgs e)
        {
            try
            {
                if ((decimal)this.numFirstWeight.Value > 0)
                {
                    // Exists First weight
                    this.numFirstWeight.Enabled = false;
                    if ((decimal)this.numSecondWeight.Value > 0)
                    {
                        this.numSecondWeight.Enabled = false;
                    }
                    else
                    {
                        // Check get second weight
                        // this.rdtSecondWeight.Checked = true;
                        this.numSecondWeight.Enabled = true;
                        this.numSecondWeight.Focus();
                    }
                }
                else
                {
                    // Check get first weight
                    // this.rdtFirstWeight.Checked = true;
                    this.numFirstWeight.Enabled = true;
                    this.numFirstWeight.Focus();
                }

                if (rdtFirstWeight.Checked)
                {
                    can = true;                  
                }
                else
                {
                    can = false;
               
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi mở cân : "+ ex.Message);
            }
        }

        private void LoadData()
        {
            IProductDAO dao = new ProductDAO();
            IList<ProductModel> products = dao.GetAll();
            if (products != null)
            {
                this.cboProductID.DataSource = products;
                this.cboProductID.ValueMember = "ProductName";
                this.cboProductID.DisplayMember = "ProductID";

                this.cboProductID.Text = String.Empty;
            }

            cboProductID.ValueChanged += new EventHandler(cboProductID_SelectedValueChanged);

            IVendorDAO dao1 = new VendorDAO();
            IList<VendorModel> vendors = dao1.GetAll();
            if (vendors != null)
            {
                this.cboVendorID.DataSource = vendors;
                this.cboVendorID.ValueMember = "VendorName";
                this.cboVendorID.DisplayMember = "VendorID";

                this.cboVendorID.Text = String.Empty;
            }

            cboVendorID.ValueChanged += new EventHandler(cboVendorID_SelectedValueChanged);
        }

        bool ValidData()
        {
            if ((decimal)this.numFirstWeight.Value == 0)
            {
                Common.ShowAlert(Resources.NotInputFirstWeight);
                this.numFirstWeight.Focus();
                return false;
            }
            if (this.txtVehicleID.Text == String.Empty)
            {
                Common.ShowAlert(Resources.NotInputVehicle);
                this.txtVehicleID.Focus();
                return false;
            }
            if ((decimal)this.numSecondWeight.Value > 0)
            {
                if ((decimal)this.numFirstWeight.Value > (decimal)this.numSecondWeight.Value && cboPoType.SelectedIndex == 2)
                {
                    Common.ShowAlert(Resources.NotInput);
                    this.cboPoType.Focus();
                    return false;
                }
                if ((decimal)this.numFirstWeight.Value < (decimal)this.numSecondWeight.Value && cboPoType.SelectedIndex == 1)
                {
                    Common.ShowAlert(Resources.NotOutput);
                    this.cboPoType.Focus();
                    return false;
                }
            }

            return true;
        }
        
        private void ResetDetails()
        {
            this.txtVehicleID.Text = String.Empty;
            this.numFirstWeight.Text = String.Empty;
            this.numSecondWeight.Text = String.Empty;

            this.txtIOCode.Focus();
        }

        public List<string[]> parseCSV(string path)
        {
            List<string[]> parsedData = new List<string[]>();

            try
            {
                using (StreamReader readFile = new StreamReader(path))
                {
                    string line;
                    string[] row;

                    while ((line = readFile.ReadLine()) != null)
                    {
                        row = line.Split(',');
                        parsedData.Add(row);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            return parsedData;
        }

        #endregion

        /// <summary>
        /// Load serial port method.
        /// </summary>

        #region OpenSerialPort
        private void OpenSerialPort()
        {
            try
            {
                if (!Common.Port.IsOpen) Common.Port.Open();
               // WriteLog("Open Com1");
                Common.Port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            }
            catch (Exception ex)
            {
                if (this.gridEXPo.CurrentRow != null &&
                    !(this.gridEXPo.CurrentRow.DataRow as POModel).IsNew)
                {
                    Common.ShowAlert(Resources.CannotOpenPort, ex.Message,
                        Common.Port.PortName,
                        Common.Port.Parity,
                        Common.Port.StopBits,
                        Common.Port.BaudRate,
                        Common.Port.DataBits);
                }
                else
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
        // Open ComPort 2
        private void OpenSerialPort2()
        {
            try
            {
                
                    if (!Common.Port2.IsOpen) Common.Port2.Open();
                   // WriteLog("Open Com2");
                    Common.Port2.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived2);
                
            }
            catch (Exception ex)
            {
                if (this.gridEXPo.CurrentRow != null &&
                    !(this.gridEXPo.CurrentRow.DataRow as POModel).IsNew)
                {
                    Common.ShowAlert(Resources.CannotOpenPort, ex.Message,
                        Common.Port2.PortName,
                        Common.Port2.Parity,
                        Common.Port2.StopBits,
                        Common.Port2.BaudRate,
                        Common.Port2.DataBits);
                }
                else
                {
                    Debug.WriteLine(ex.Message);
                }
            }
        }
        #endregion

        /// <summary>
        /// Load serial port method.
        /// </summary>
       
        #region FreeSerialPort
        //Port 1
        private void FreeEventSerialPort()
        {
            try
            {
                Common.Port.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
                //WriteLog("Release Com1");
            }
            catch (Exception ex)
            {
                Common.ShowAlert(Resources.CannotClosePort, ex.Message,
                        Common.Port.PortName,
                        Common.Port.Parity,
                        Common.Port.StopBits,
                        Common.Port.BaudRate,
                        Common.Port.DataBits);
            }
        }
        
        //Port 2
        private void FreeEventSerialPort2()
        {
            try
            {
                Common.Port2.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived2);
                //WriteLog("Release Com2");
            }
            catch (Exception ex)
            {
                Common.ShowAlert(Resources.CannotClosePort, ex.Message,
                        Common.Port2.PortName,
                        Common.Port2.Parity,
                        Common.Port2.StopBits,
                        Common.Port2.BaudRate,
                        Common.Port2.DataBits);
            }
        }
        #endregion             
        

        #region Serial Port Events

        string _data = String.Empty;

        /// <summary>
        /// Event Receive Data From Scale Device.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                //string vehicleID = txtVehicleID.Text.Trim();
                //if (vehicleID.Length > 0 && this.chkInputScale.Checked)

                if (this.chkInputScale.Checked && can==true)
                {
                    string dataReceived=string.Empty;
                   
                    dataReceived = Common.Port.ReadExisting();
                    
                   // WriteLog("Start receive data");

                    // Data:
                    // 4B 47 4D 0D 0A 02 20 20 20 20 33 33 38 30 4B 47
                    _data = String.Concat(_data, dataReceived);
                    //WriteLog(_data);

                    // Get String with Start Index
                    //byte sByte = 0x2B;
                    // chuoi truyen moi: P+0012345
                    byte sByte = 0x2B;
                    //byte eByte = 0x6B; // k

                    int startIndex = _data.IndexOf(Convert.ToChar(sByte));    // index = 0x02;
                    if (startIndex >= 0 && _data.Length > 10)
                    {
                        _data = _data.Substring(startIndex + 2,5);
                        ParingData(_data);
                        _data = String.Empty;
                       // WriteLog("Start: " + _data);
                        //WriteLog("Have start byte");
                    }


                    //// Get String with End Index and Print It.
                    //int endIndex = _data.IndexOf(Convert.ToChar(eByte));

                    //if (endIndex >= 0 && _data.Length >4)
                    //{
                        
                    //    _data = _data.Trim();
                    //    _data = _data.Substring(0, endIndex);
                      
                    //    //Console.WriteLine(_data);

                    //    //WriteLog("End 2: " + _data);
                    //    //WriteLog("Have end byte");

                    //    // Print it
                    //    ParingData(_data);
                    //    _data = String.Empty;
                    //}
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Receive data failed. Error details: " + ex.Message);
            }
        }
        private void SerialPort_DataReceived2(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                //string vehicleID = txtVehicleID.Text.Trim();
                //if (vehicleID.Length > 0 && this.chkInputScale.Checked)
                if (this.chkInputScale.Checked && can == false)
                {
                    string dataReceived = string.Empty;
                   
                    dataReceived = Common.Port2.ReadExisting();
                    
                    // WriteLog("Start receive data");

                    // Data:
                    // 4B 47 4D 0D 0A 02 20 20 20 20 33 33 38 30 4B 47
                    _data = String.Concat(_data, dataReceived);
                    //WriteLog(_data);

                    // Get String with Start Index
                    //byte sByte = 0x2B;
                    // chuoi truyen moi: P+0012345
                    byte sByte = 0x2B;
                    //byte eByte = 0x6B; // k

                    int startIndex = _data.IndexOf(Convert.ToChar(sByte));    // index = 0x02;
                    if (startIndex >= 0 && _data.Length > 10)
                    {
                        _data = _data.Substring(startIndex + 2, 5);
                        ParingData(_data);
                        _data = String.Empty;
                        // WriteLog("Start: " + _data);
                        //WriteLog("Have start byte");
                    }


                    //// Get String with End Index and Print It.
                    //int endIndex = _data.IndexOf(Convert.ToChar(eByte));

                    //if (endIndex >= 0 && _data.Length >4)
                    //{

                    //    _data = _data.Trim();
                    //    _data = _data.Substring(0, endIndex);

                    //    //Console.WriteLine(_data);

                    //    //WriteLog("End 2: " + _data);
                    //    //WriteLog("Have end byte");

                    //    // Print it
                    //    ParingData(_data);
                    //    _data = String.Empty;
                    //}
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Receive data failed. Error details: " + ex.Message);
            }
        }
       
        #region Receiving Data From COM Port
        private void ParingData(string data)
        {
            //WriteLog("Result: " + data);

            //WriteLog(String.Format("First focused: {0}", this.ActiveControl.Equals(numFirstWeight)));
            //WriteLog(String.Format("Second focused: {0}", this.ActiveControl.Equals(numSecondWeight)));

            bool b = (CurrentPO != null && CurrentPO.SecondWeight > 0);
            if (!b)
            {
                // if (!CurrentPO.HasFirstWeight)
                if (this.ActiveControl.Equals(numFirstWeight))
                {
                    //MessageBox.Show("Cân 1: " + data);
                    this.numFirstWeight.Invoke(new EventHandler(delegate
                    {
                        this.numFirstWeight.Value = Int32.Parse(data);
                    }));
                }
                // else if (!CurrentPO.HasSecondWeight)
                else if (this.ActiveControl.Equals(numSecondWeight))
                {
                    //MessageBox.Show("Cân 2" + data);
                    this.numSecondWeight.Invoke(new EventHandler(delegate
                    {
                        this.numSecondWeight.Value = Int32.Parse(data);
                    }));
                }
            }
        }
        #endregion

        /// <summary>
        /// Event on activated
        /// </summary>
        /// <param name="e"></param>
        protected override void OnActivated(EventArgs e)
        {
            OpenSerialPort();
            OpenSerialPort2();
            FrmMDI.Instance.menuStrip1.Enabled = false;
            base.OnActivated(e);
        }

        protected override void OnDeactivate(EventArgs e)
        {
            FreeEventSerialPort();
            FreeEventSerialPort2();
            FrmMDI.Instance.menuStrip1.Enabled = true;
            base.OnDeactivate(e);
        }

        #endregion

        //private void WriteLog(string message)
        //{
        //    if (!File.Exists(Common.logfile))
        //        File.Create(Common.logfile);
        //    using (StreamWriter w = File.AppendText(Common.logfile))
        //    {
        //        w.WriteLine(String.Format("{0:d} {0:HH:mm} - {1}", DateTime.Now, message));
        //        // Close the writer and underlying file.
        //        w.Flush();
        //        w.Close();
        //    }
        //}
    }
}